﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TDLib.UIs.Forms;
using TDLib.Utils;
using FeiXunHelper.Services;
using FeiXunHelper.UIs.Common;

namespace FeiXunHelper.UIs.Login
{
    public partial class FrmLogin : FrmIconBase
    {
        private FeiXunService _service = null;
        public FrmLogin(FeiXunService service)
        {
            InitializeComponent();
            _service = service;
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string mobile = this.textBox1.Text.Trim();
            string pwd = this.textBox2.Text.Trim();
            if (mobile.Length < 1)
            {
                MsgBox.Warning("手机号不能为空！");
                return;
            }
            if (pwd.Length < 1)
            {
                MsgBox.Warning("密码不能为空！");
                return;
            }

            RunTaskThread(() => {
                this.button1.Text = "登录中";
                this.button1.Enabled = false;
                this.button2.Enabled = false;
                this.buttonFastLogin.Enabled = false;
                bool isSuccess = false;
                try
                {
                    _service.Login(mobile, pwd);
                    isSuccess = true;
                }
                catch (Exception ex)
                {
                    MsgBox.Error("登录失败，" + ex.Message);
                    this.button1.Enabled = true;
                    this.button2.Enabled = true;
                    this.buttonFastLogin.Enabled = true;
                    this.button1.Text = "登录";
                }

                if (isSuccess)
                {
                    this.DialogResult = System.Windows.Forms.DialogResult.OK; 
                }
            });
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
        }

        private void buttonFastLogin_Click(object sender, EventArgs e)
        {
            var mobiles = ConfigStorate.ReadAllUsers();
            ContextMenuStrip cms = new ContextMenuStrip();
            foreach (var mobile in mobiles)
            {
                cms.Items.Add(mobile, null, (o, args) => { 
                    var control = o as ToolStripItem;
                    var m = control.Text;
                    string cookie = ConfigStorate.ReadUserCookie(m);
                    _service.SetCookie(cookie);
                    this.DialogResult = System.Windows.Forms.DialogResult.OK; 
                });
            }
            if (mobiles.Count < 1)
            {
                cms.Items.Add("无", null, null);
            }
            cms.Show(this.buttonFastLogin, new Point(0,this.buttonFastLogin.Height+2));
        }
    }
}
